package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/app/model"
	"FeedXmh/redis"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"paco_toolkit/DMXFGW"
)

var Feednode_replace = feednode_replace{}

type feednode_replace struct {
}

func (a *feednode_replace) GetPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	id := gconv.String(params["id"])
	old_sn := gconv.String(params["old_sn"])
	new_sn := gconv.String(params["new_sn"])
	step := gconv.String(params["step"])
	status := gconv.String(params["status"])
	unfinished := gconv.String(params["unfinished"])
	key := gconv.String(params["key"])

	where := " 1=1 and step>0 "
	if id != "" {
		where += " and id=" + id
	}
	if old_sn != "" {
		where += fmt.Sprintf(" and old_sn='%s'", old_sn)
	}
	if new_sn != "" {
		where += fmt.Sprintf(" and new_sn='%s'", new_sn)
	}
	if step != "" {
		where += fmt.Sprintf(" and step in (%s) ", step)
	}
	if status != "" {
		where += fmt.Sprintf(" and status='%s'", status)
	}
	if unfinished != "" {
		where += fmt.Sprintf(" and step<7 ")
	}
	if key != "" {
		where += " and CONCAT(old_sn,new_sn) LIKE '%" + key + "%'"
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("v_hzfgw_node_replace")
		count, err := model.Where(where).Count()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			res["count"] = count
			start := limit*page - limit
			if start < 0 {
				start = 0
			}
			if order != "" {
				model = model.Order(order)
			} else {
				model = model.Order(" id desc ")
			}
			records, error := model.Limit(start, limit).All()
			if error != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := records.List()
				res["code"] = 0
				res["data"] = list
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feednode_replace) Post(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	params := r.GetFormMap()
	old_sn := gconv.String(params["old_sn"])
	new_sn := gconv.String(params["new_sn"])
	reason := gconv.String(params["reason"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		nodeList, err := dao.V_hzgw_node.GetList(fmt.Sprintf(" sn=%s and gw_alive is NOT null", old_sn))
		if err != nil {
			g.Log().Line(true).Error()
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			if len(nodeList) == 0 {
				res["code"] = -2
				res["msg"] = "错误,请检查SN是否正确，检查智能终端是否在线。"
			} else {
				//判断网关是否在线
				node := nodeList[0]
				addr := gconv.String(node["addr"])
				tn := gconv.Int(node["tn"])
				feed_plan_id := gconv.Int(node["feed_plan_id"])
				deviceList, err := dao.T_device.GetList(fmt.Sprintf(" device_addr='%s' ", addr))
				if err != nil {
					g.Log().Line(true).Error()
					res["code"] = -1
					res["msg"] = err.Error()
				} else {
					if len(deviceList) == 0 {
						res["code"] = -3
						res["msg"] = "系统未找到智能终端关联信息，请确认是否填写正确"
					} else {
						device := deviceList[0]
						alive := gconv.Int(device["alive"])
						if alive == 0 {
							res["code"] = -4
							res["msg"] = "当前智能终端离线，无法执行流程"
						} else {

							//查看是否有在运行的终端和饲喂器，有则提示需要等待
							rd, err := db.GetAll(fmt.Sprintf("SELECT * FROM t_hzfgw_node_replace WHERE (new_sn='%s' or old_sn='%s' or addr='%s') and step<7;", new_sn, old_sn, addr))
							if err != nil {
								g.Log().Line(true).Error()
								res["code"] = -5
								res["msg"] = err.Error()
							} else {
								var exits bool
								if rd.Len() > 0 {
									exits = true
								} else {
									exits = false
								}
								if exits {
									res["code"] = -6
									res["msg"] = "当前饲喂器/终端已经存在运行的流程,请等待其完成结束后再尝试"
								} else {
									//启动流程
									var db_err error

									//备份参数
									var para_str string
									para, _ := db.GetOne(fmt.Sprintf(" SELECT data as para_str FROM t_hzfgw_node_para WHERE sn='%s'; ", old_sn))
									if para == nil {
										para, _ = db.GetOne(fmt.Sprintf(" SELECT new_data as para_str FROM t_hzfgw_node_para_his WHERE sn='%s' ORDER BY his_date DESC LIMIT 1; ", old_sn))
									}
									if para == nil {
										str := fmt.Sprintf(" %s 无法找到参数用于备份", old_sn)
										g.Log().Line(true).Warning(str)
										res["code"] = -7
										res["msg"] = str
									} else {
										para_str = gconv.String(para.Map()["para_str"])
										fp := DMXFGW.FNodePara{}
										gjson.DecodeTo(para_str, &fp)
										//fp.Sn = old_sn
										redis.SetGwNodeBakupPara(addr, old_sn, para_str)

										//清除旧饲喂器告警
										_, db_err = db.Exec(fmt.Sprintf(" DELETE FROM t_alarm WHERE sn='%s'; ", old_sn))
										if db_err == nil {
											//清除旧饲喂器状态
											_, db_err = db.Exec(fmt.Sprintf(" DELETE FROM t_hzfgw_node_status WHERE sn='%s'; ", old_sn))

											//删除新饲喂器的历史状态(新饲喂器可能再别处用过)
											if db_err == nil {
												_, db_err = db.Exec(fmt.Sprintf(" DELETE FROM t_hzfgw_node_status_his WHERE sn='%s'; ", new_sn))
											}
										}
										/*if db_err == nil {
											//清除旧饲喂器参数
											_, db_err = db.Exec(fmt.Sprintf(" DELETE FROM t_hzfgw_node_para WHERE sn='%s'; ", old_sn))
										}*/
										if db_err == nil {
											//把status_his的sn替换为新饲喂器的sn
											_, db_err = db.Exec(fmt.Sprintf(" UPDATE t_hzfgw_node_status_his SET sn='%s' WHERE sn='%s'; ", new_sn, old_sn))
										}

										if db_err != nil {
											res["code"] = -8
											res["msg"] = "Clear Err!启动流程失败"
										} else {
											item := gdb.Map{
												"step":         1,
												"status":       model.FeedNodeReplaceStatusDone,
												"old_sn":       old_sn,
												"new_sn":       new_sn,
												"addr":         addr,
												"tn":           tn,
												"feed_plan_id": feed_plan_id,
												"reason":       reason,
												"create_user":  userid,
												"create_date":  gtime.Now().String(),
											}
											_, db_err = dao.T_hzfgw_node_replace.Save(item)
											if db_err != nil {
												res["code"] = -9
												res["msg"] = "DB Err!启动流程失败"
											} else {
												res["code"] = 0
												res["msg"] = "OK"
											}
										}

									}
								}
							}

						}
					}
				}
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feednode_replace) DELETE(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	id, exist := params["id"]
	if exist {
		claims := jwt.ExtractClaims(r)
		current_user := claims["userid"].(string)
		url := r.URL.Path
		//db:=g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission(url, r.Method, current_user) {
			_, err := dao.T_hzfgw_node_replace.Delete(gconv.String(id))
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	} else {
		res["code"] = -1
		res["msg"] = "错误的参数"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
